<template xmlns="http://www.w3.org/1999/html">
  <div style="margin-left: 20px;margin-top: 20px">
    <div class="container">
      <el-input v-model="input" class="input-field" style="width: 300px" placeholder="请输入名称" />
      <el-button class="input-field" type="primary" icon="el-icon-search" @click="ck">查询</el-button>
      <el-button type="warning" icon="el-icon-circle-plus" @click="showFormxz">新增</el-button>

      <el-button type="success" icon="el-icon-edit" @click="showcds"> 授予/收回角色菜单</el-button>
      <el-button type="info" icon="el-icon-edit" @click="showqxs"> 授予/收回角色权限</el-button>

    </div>

    <br>

    <el-table v-loading="loading" :data="displayedData" style="">
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-checkbox v-model="scope.row.checked" @change="saveid(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column v-if="showColumnid" prop="id" label="角色编号" />
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="keyword" label="角色关键字" />
      <el-table-column prop="description" label="角色描述" />
      <el-table-column prop="description" label="操作">
        <!-- 使用v-for循环渲染按钮 -->
        <template v-slot="scope">
          <el-button type="primary" icon="el-icon-edit" @click="showEditForm(scope.row.id)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <br>

    <el-pagination
      style="float: right"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalItems"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog title="授予/收回角色权限" :visible.sync="showqx">
      <div>
        <div v-for="(parentMenu, index) in qxs" :key="index">
          <br>
          <label :for="parentMenu.id">
            <input :id="'qx'+parentMenu.id" type="checkbox" :value="parentMenu.id" @click="qxcick(parentMenu.id)">
            {{ parentMenu.name }}
          </label>
          <br>
        </div>
      </div>
      <el-button type="primary" @click="addqx">确定</el-button>
      <el-button @click="gbqx">取消</el-button>
    </el-dialog>

    <el-dialog title="授予/收回角色菜单" :visible.sync="showcd">
      <div>
        <div v-for="(parentMenu, index) in fMenus" :key="index">
          <label :for="parentMenu.id">
            <input :id="parentMenu.id" type="checkbox" @click="handleParentMenuClick(parentMenu.id)">
            {{ parentMenu.name }}
          </label>
          <div :id="'z'+parentMenu.id">
            <ul>
              <li v-for="(childMenu, childIndex) in parentMenu.children" :key="childIndex">
                <label :for="childMenu.id">
                  <input :id="'z'+childMenu.id" type="checkbox" :value="childMenu.id" @click="zhandleParentMenuClick(parentMenu.id,childMenu.id)">
                  {{ childMenu.name }}
                </label>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <el-button type="primary" @click="adddelcd">确定</el-button>
      <el-button @click="gbcd">取消</el-button>
    </el-dialog>

    <el-dialog title="新增" :visible.sync="showForm">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="角色关键字" prop="keyword">
          <el-input v-model="ruleForm.keyword" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="ruleForm.description" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
          <el-button @click="resetForm('ruleForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="编辑" :visible.sync="showFormxg">
      <el-form ref="rulexgForm" :model="rulexgForm" :rules="rules" label-width="100px">
        <el-form-item label="编号">
          <el-input v-model="rulexgForm.id" readonly />
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="rulexgForm.name" />
        </el-form-item>
        <el-form-item label="角色关键字" prop="keyword">
          <el-input v-model="rulexgForm.keyword" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="rulexgForm.description" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitFormxg('rulexgForm')">确定</el-button>
          <el-button @click="resetFormxg('rulexgForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>

</template>
<style>

.container {
  display: flex;
  align-items: center;
}

.input-field {
  margin-right: 10px; /* 调整元素之间的间距 */

}

</style>
<script>
import row from 'element-ui/packages/row'
import axios from 'axios'
import { configureWebpack as nestedMenu } from '../../../vue.config'
import getters from '@/store/getters'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      account: '',
      jsid: 0,
      del: [],
      add: [],
      qxdel: [],
      qxadd: [],
      childIds: [], // 角色的菜单
      parentIds: [], // 角色的菜单
      fMenus: [], // 父菜单
      zMenus: [], // 子菜单
      selectedMenus: [],
      menus: [],
      qxs: [], // 权限
      showcd: false,
      showqx: false,
      message: '', // 返回结果成功没
      article: '',
      loading: true,
      input: '',
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示的条数
      totalItems: 0, // 总条数
      activeName: 'first',
      showFormxg: false, // 控制修改表单的显示
      showForm: false, // 控制添加表单的显示状态，默认隐藏
      showColumnid: false, // 控制id数据的隐藏
      showbz: false, // 控制备注数据隐藏
      displayedData: [], // 分页后的

      rulexgForm: {
        description: '',
        keyword: '',
        name: '',
        id: ''
      },
      ruleForm: {
        description: '',
        keyword: '',
        name: ''
      },

      rules: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        keyword: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      },
      rules2: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        keyword: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      }

    }
  },
  computed: {
    nestedMenu() {
      return nestedMenu
    },
    row() {
      return row
    },
    ...mapGetters(['token'])
  },
  mounted() {
    // 最初调用loadData()方法以填充表格
    const est = {}
    est.name = this.input
    this.fetchArticle(est)
    console.log(this.token)
    const commaIndex = this.token.indexOf(',')
    this.account = this.token.substring(0, commaIndex)
  },
  created() {
    setInterval(this.myMethod, 1000) // 每3秒执行一次myMethod方法
    setInterval(this.qxMethod, 1000) // 每3秒执行一次方法
  },
  methods: {
    qxMethod() {
      if (this.showqx === false) {
        this.qxs = []
      }
    },
    myMethod() {
      if (this.showcd === false) {
        this.fMenus = []
      }
    },
    adddelcd() {
      this.fMenus = []
      this.showcd = false
      const est = {}
      est.roleid = this.jsid
      est.add = this.add
      est.del = this.del
      this.adddel(est)
      this.add = []
      this.del = []
    },
    gbcd() {
      this.fMenus = []
      this.showcd = false
      this.add = []
      this.del = []
    },
    addqx() {
      this.qxs = []
      this.showqx = false
      const est = {}
      est.roleid = this.jsid
      est.add = this.qxadd
      est.del = this.qxdel
      this.adddelqx(est)
      this.qxadd = []
      this.qxdel = []
    },
    gbqx() {
      this.qxs = []
      this.showqx = false
    },
    qxcick(id) {
      const che = document.getElementById('qx' + id).checked
      if (che === false) {
        const index = this.qxadd.indexOf(id)
        if (index > -1) {
          this.qxadd.splice(index, 1)
        } else {
          this.qxdel.push(id)
        }
      } else {
        const index = this.qxdel.indexOf(id)
        if (index > -1) {
          this.qxdel.splice(index, 1)
        } else {
          this.qxadd.push(id)
        }
      }
    },
    zhandleParentMenuClick(id, zid) {
      const parentCheckbox = document.getElementById(id) // 获取父菜单复选框元素
      const divId = 'z' + id
      const childCheckboxes = document.querySelectorAll(`#${divId} input[type="checkbox"]:checked`)
      const checked = document.querySelectorAll('input[id="z' + zid + '"]:checked')// 获得当前选中的子菜单
      checked.forEach(checkbox => {
        // 获得选中的子菜单
        const index = this.del.indexOf(checkbox.value)
        if (index > -1) {
          this.del.splice(index, 1)
        } else {
          this.add.push(checkbox.value)
        }
      })
      const uncheckedCheckboxes = document.querySelectorAll(`input[id="z${zid}"]:not(:checked)`)// 获得当前未选中的
      uncheckedCheckboxes.forEach(checkbox => {
        // 获得取消选中的子菜单
        const index = this.add.indexOf(checkbox.value)
        if (index > -1) {
          this.add.splice(index, 1)
        } else {
          this.del.push(checkbox.value)
        }
      })
      const selectedChildCount = childCheckboxes.length // 获取选中的子菜单数量
      if (selectedChildCount > 0) {
        const index = this.del.indexOf(id)
        if (index > -1) {
          this.del.splice(index, 1)
        } else if (document.getElementById(id).checked === true) {
          // 如果默认父菜单是选中的话就进行处理
        } else {
          this.add.push(id)
        }
        // 一定要判断完在选中父菜单不然就进else if了
        parentCheckbox.checked = true
      } else {
        // 所有子菜单未选中
        parentCheckbox.checked = false
        const index = this.add.indexOf(id)
        if (index > -1) {
          this.add.splice(index, 1)
        } else {
          this.del.push(id)
        }
      }
    },
    handleParentMenuClick(id) {
      // 子菜单选中的话
      if (document.getElementById(id).checked === true) {
        const divId = 'z' + id
        // 获得所有未选中的子菜单
        const checkboxes = document.querySelectorAll(`#${divId} input[type="checkbox"]:not(:checked)`)
        checkboxes.forEach(checkbox => {
          // 处理每个复选框
          checkbox.checked = true
          const index = this.del.indexOf(checkbox.value)
          if (index > -1) {
            this.del.splice(index, 1)
          } else {
            this.add.push(checkbox.value)
          }
        })
        const index = this.del.indexOf(id)
        if (index > -1) {
          this.del.splice(index, 1)
        } else {
          this.add.push(id)
        }
      } else {
        const divId = 'z' + id
        // 获得所有选中的子菜单
        const checkboxes = document.querySelectorAll(`#${divId} input[type="checkbox"]:checked`)
        checkboxes.forEach(checkbox => {
          // 处理每个复选框
          checkbox.checked = false

          const index = this.add.indexOf(checkbox.value)
          if (index > -1) {
            this.add.splice(index, 1)
          } else {
            this.del.push(checkbox.value)
          }
        })
        const index = this.add.indexOf(id)
        if (index > -1) {
          this.add.splice(index, 1)
        } else {
          this.del.push(id)
        }
      }
    },
    open(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击 "确定" 按钮时执行删除操作
        this.deleteItem(id) // 传递 id 参数
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    deleteItem(id) {
      this.deletees(id)
      // 在这里执行删除操作，使用传递的 id 参数
      // 可以调用你的删除方法，传递 id 参数
      // 例如：this.$axios.delete(`/api/items/${id}`)
      // 然后处理成功和失败的情况
      // 成功：显示删除成功的消息
      // 失败：显示删除失败的消息
    },
    // 当每页显示条数发生变化时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      // 根据新的每页显示条数重新加载数据
      this.loadData()
    },

    // 当前页码发生变化时触发
    handleCurrentChange(val) {
      this.currentPage = val
      // 根据新的当前页码重新加载数据
      this.loadData()
    },
    // 根据当前页和每页显示的数量加载数据
    loadData() {
      console.log(this.article)
      const startIndex = (this.currentPage - 1) * this.pageSize// 得到当前页从哪一页显示的
      const endIndex = startIndex + this.pageSize// 得到下一页的页
      this.displayedData = this.article.slice(startIndex, endIndex)// （5，10）显示的是第二页的
      this.loading = false
    },
    // 确定添加
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')

          // 在验证通过后获取表单数据
          const formData = { ...this.ruleForm }
          console.log(formData)

          // 执行其他操作，例如发送表单数据到后端
          this.addes(formData)
          this.$refs[formName].resetFields()
          this.showForm = false
        } else {
          alert('error submit!!')
          return false
        }
      })
    },
    // 确定修改
    submitFormxg(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
          const formData = { ...this.rulexgForm }
          this.updatees(formData)
          this.$refs[formName].resetFields()
          this.showFormxg = false
        } else {
          alert('error submit!!')
          return false
        }
      })
    },
    // 显示菜单页面
    showcds(row) {
      if (this.jsid > 0) {
        let bianliang
        const permissions = getters.permissions(this.$store.state)
        permissions.forEach(permission => {
          const keyword = permission.keyword
          console.log(keyword)
          if (keyword === 'adddelmenu') {
            bianliang = 1
          }
        })
        if (bianliang === 1) {
          this.showcd = true
          const dto = {}
          dto.account = this.account
          this.selectmenu(dto)
        } else {
          alert('抱歉你没有这个权限')
        }
      } else {
        alert('请选择一个角色')
      }
    },

    // 显示权限页面
    showqxs(row) {
      if (this.jsid > 0) {
        let bianliang
        const permissions = getters.permissions(this.$store.state)
        permissions.forEach(permission => {
          const keyword = permission.keyword
          console.log(keyword)
          if (keyword === 'adddelqx') {
            bianliang = 1
          }
        })
        if (bianliang === 1) {
          this.showqx = true
          const dto = {}
          dto.account = this.account
          this.selectqx(dto)
        } else {
          alert('抱歉你没有这个权限')
        }
      } else {
        alert('请选择一个角色')
      }
    },
    // 显示添加页面
    showFormxz() {
      let bianliang
      const permissions = getters.permissions(this.$store.state)
      permissions.forEach(permission => {
        const keyword = permission.keyword
        console.log(keyword)
        if (keyword === 'addrole') {
          bianliang = 1
        }
      })
      if (bianliang === 1) {
        this.showForm = true
      } else {
        alert('抱歉你没有这个权限')
      }
    },
    saveid(row) {
      if (row.checked) {
        this.jsid = row.id
      } else {
        this.jsid = 0
      }
    },
    // 显示修改页面
    showEditForm(id) {
      let bianliang
      const permissions = getters.permissions(this.$store.state)
      permissions.forEach(permission => {
        const keyword = permission.keyword
        console.log(keyword)
        if (keyword === 'updaterole') {
          bianliang = 1
        }
      })
      if (bianliang === 1) {
        const data = this.displayedData.find((user) => user.id === id)
        this.showFormxg = true
        // 给修改页面赋值
        this.rulexgForm.name = data.name
        this.rulexgForm.description = data.description
        this.rulexgForm.id = data.id
        this.rulexgForm.keyword = data.keyword
      } else {
        alert('抱歉你没有这个权限')
      }
    },
    // 添加页面取消
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.showForm = false
    },
    // 修改页面取消
    resetFormxg(formName) {
      this.$refs[formName].resetFields()
      this.showFormxg = false
    },
    // 查询名称方法
    ck() {
      const est = {}
      est.name = this.input
      this.fetchArticle(est)
    },
    // 查询方法
    async fetchArticle(est) {
      console.log(est)
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post('/api/role/query', est, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        // eslint-disable-next-line no-unused-vars
        const { code, flag, message, data } = response.data
        this.article = data
        this.message = message
        this.totalItems = this.article.length
        this.loadData()
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    },

    async addes(est) {
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post('/api/role/add', est, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const { code, flag, message, data } = response.data
        this.message = message
        this.totalItems = this.article.length
        const est2 = {}
        this.fetchArticle(est2)
        alert(this.message)
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    },

    async adddel(est) {
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post('/api/role/adddelmenu', est, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const { code, flag, message, data } = response.data
        this.message = message
        this.totalItems = this.article.length
        alert(this.message)
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    },

    async adddelqx(est) {
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post('/api/role/adddelqx', est, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const { code, flag, message, data } = response.data
        this.message = message
        this.totalItems = this.article.length
        alert(this.message)
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    },

    async updatees(est) {
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post('/api/role/update', est, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const { code, flag, message, data } = response.data
        this.message = message
        this.totalItems = this.article.length
        const est2 = {}
        this.fetchArticle(est2)
        alert(this.message)
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    },

    async deletees(id) {
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post(`/api/estimate/deletees/${id}`, null, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const { code, flag, message, data } = response.data
        this.message = message
        console.log(this.article)
        this.totalItems = this.article.length
        const est2 = {}
        this.fetchArticle(est2)
        alert(this.message)
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    },
    // 获取登录账户所有的菜单
    async selectmenu(dto) {
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post(`/api/role/querymenu/`, dto, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const map = response.data
        this.menus = map
        const parsedMenus = []
        for (const parentIdStr in this.menus) {
          if (Object.prototype.hasOwnProperty.call(this.menus, parentIdStr)) {
            var keyValueArray = parentIdStr.split(',') // 将键值部分按逗号分隔成数
            // var menuid = keyValueArray[0].split("=")[1]  menuid=9'根据=分割成数组【1】代表数组第二个值就是9
            var menuid = keyValueArray[0].split('=')[1] // 提取 menuid 的值
            var menuname = keyValueArray[1].split('=')[1] // 提取 menuname 的值
            console.log('id:', menuid)
            console.log('name:', menuname)
            const parentMenu = {

              id: menuid,
              name: menuname,
              children: this.menus[parentIdStr].map(child => ({
                id: child.id,
                name: child.name
              }))
            }
            this.$set(parsedMenus, parsedMenus.length, parentMenu)
          }
        }

        this.fMenus = parsedMenus
        // 现在，parsedMenus 包含了解析后的数据结构
        const dto2 = {}
        dto2.account = this.account
        dto2.roleid = this.jsid
        this.selectmenu2(dto2)
        console.log(parsedMenus)
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    }, // 获取登录账户角色的菜单
    async selectmenu2(dto) {
      try {
        const response = await axios.post(`/api/role/queryzmenu/`, dto, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const map = response.data
        this.menus = map
        const parsedMenus = []
        const parentIds = []
        const childIds = []

        for (const parentIdStr in this.menus) {
          if (Object.prototype.hasOwnProperty.call(this.menus, parentIdStr)) {
            var keyValueArray = parentIdStr.split(',')
            var menuid = keyValueArray[0].split('=')[1]
            var menuname = keyValueArray[1].split('=')[1]

            const parentMenu = {
              id: menuid,
              name: menuname,
              children: this.menus[parentIdStr].map(child => ({
                id: child.id,
                name: child.name
              }))
            }

            parsedMenus.push(parentMenu)
            parentIds.push(menuid) // 将当前父菜单的 id 添加到 parentIds 数组中

            this.menus[parentIdStr].forEach(child => {
              childIds.push(child.id) // 将当前子菜单的 id 添加到 childIds 数组中
            })
          }
        }

        this.zMenus = parsedMenus
        this.parentIds = parentIds
        this.childIds = childIds
        console.log('Parent IDs:', parentIds)
        console.log('Child IDs:', childIds)
        for (let i = 0; i < parentIds.length; i++) {
          document.getElementById(parentIds[i]).checked = true
        }
        for (let i = 0; i < childIds.length; i++) {
          document.getElementById('z' + childIds[i]).checked = true
        }
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    },
    // 获取登录账户所有的权限
    async selectqx(dto) {
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post(`/api/role/queryqx/`, dto, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const map = response.data
        this.qxs = map
        // 现在，parsedMenus 包含了解析后的数据结构
        const dto2 = {}
        dto2.account = this.account
        dto2.roleid = this.jsid
        this.selectzqx(dto2)
        console.log(map)
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    },
    // 获取登录账户角色的权限
    async selectzqx(dto) {
      try {
        // 发送POST请求并设置Content-Type为application/json
        const response = await axios.post(`/api/role/queryzqx/`, dto, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        const map = response.data
        for (let i = 0; i < map.length; i++) {
          document.getElementById('qx' + map[i].id).checked = true
        }
      } catch (error) {
        console.error('Failed to fetch article:', error)
      }
    }

  }

}

</script>
